package action

import modelo.VirtualMachineModel

import org.codehaus.groovy.grails.commons.ApplicationHolder
import org.opennebula.client.Client
import org.opennebula.client.OneResponse
import org.opennebula.client.vm.VirtualMachine
import org.opennebula.client.vm.VirtualMachinePool

import xmlToJava.XmlUtil



class VirtualMController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

	def usuarioService
	
	def index =
	{
		redirect(action: "list")
	}
	
	def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
		
		Client client = session['usuario']
		VirtualMachinePool vmp = new VirtualMachinePool(client)
		OneResponse one = vmp.info()
		ArrayList<VirtualMachineModel> list = XmlUtil.xmlToJavaVMP(one.getMessage())
		
		ArrayList<VirtualMachineCommand> listCommand = new ArrayList<VirtualMachineCommand>() 
		list.each{
			 VirtualMachineCommand vmc = new VirtualMachineCommand()
			 atribuiVirtuaMachineModelAComando(it,vmc)
			 listCommand.add(vmc)
        }
		[vmInstanceList: listCommand, vmInstanceTotal: listCommand.size()]
    }    
    
    def acao = {
     	println(params)
    }
    	

	def console ={
		int id = Integer.parseInt(params.id)
		
		Client client = session['usuario']
		VirtualMachine vm = new VirtualMachine(id, client)
		OneResponse one = vm.info()
		VirtualMachineModel vmm = XmlUtil.xmlToJavaVM(one.getMessage())
		VirtualMachineCommand vmc = new VirtualMachineCommand()
		atribuiVirtuaMachineModelAComando(vmm,vmc)
		
		def proxy = ApplicationHolder.application.metadata['one.proxy']
		if (proxy == null)
		    proxy = vmm.template.nic.ip;
			
		
		render(view:"console", model:[virtualMachineInstance:vmc, hostInstance:proxy])  
	}


	void atribuiVirtuaMachineModelAComando(def virtualMachineModel, def virtualMachineCommand)
	{
		virtualMachineCommand.id = virtualMachineModel.id
		virtualMachineCommand.user = virtualMachineModel.userName
		virtualMachineCommand.name = virtualMachineModel.name
		virtualMachineCommand.vmState = virtualMachineModel.state
		virtualMachineCommand.lcmState = virtualMachineModel.lcmState
		virtualMachineCommand.cpu = virtualMachineModel.cpu
		virtualMachineCommand.memory = virtualMachineModel.memory
		virtualMachineCommand.host = virtualMachineModel.history.hostName
		virtualMachineCommand.vncPort = (virtualMachineModel.id + 5900) as String
		virtualMachineCommand.time = virtualMachineModel.stime

	}
	
}




class VirtualMachineCommand
{
	long id
	String user
	String name
	String vmState
	String lcmState
	long cpu
	long memory
	String host
	String vncPort
	String time	
	
}